<?php

namespace app\admin\model;

use addons\thirdwork\library\Application;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use fast\Random;
use think\Model;

class User extends Model
{

	// 表名
	protected $name = 'user';
	// 自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';
	// 追加属性
	protected $append = [
		'prevtime_text',
		'logintime_text',
		'jointime_text'
	];

	public function getOriginData()
	{
		return $this->origin;
	}

	protected static function init()
	{
		self::beforeUpdate(function ($row) {
			$changed = $row->getChangedData();
			//如果有修改密码
			if (isset($changed['password'])) {
				if ($changed['password']) {
					$salt          = \fast\Random::alnum();
					$row->password = \app\common\library\Auth::instance()->getEncryptPassword($changed['password'], $salt);
					$row->salt     = $salt;
				} else {
					unset($row->password);
				}
			}
		});


		self::beforeUpdate(function ($row) {
			$changedata = $row->getChangedData();
			$origin     = $row->getOriginData();
			if (isset($changedata['money']) && (function_exists('bccomp') ? bccomp($changedata['money'], $origin['money'], 2) !== 0 : (double) $changedata['money'] !== (double) $origin['money'])) {
				MoneyLog::create(['user_id' => $row['id'], 'money' => $changedata['money'] - $origin['money'], 'before' => $origin['money'], 'after' => $changedata['money'], 'memo' => '管理员变更金额']);
			}
			if (isset($changedata['score']) && (int) $changedata['score'] !== (int) $origin['score']) {
				ScoreLog::create(['user_id' => $row['id'], 'score' => $changedata['score'] - $origin['score'], 'before' => $origin['score'], 'after' => $changedata['score'], 'memo' => '管理员变更积分']);
			}
		});
	}

	public function getGenderList()
	{
		return ['1' => __('Male'), '0' => __('Female')];
	}

	public function getStatusList()
	{
		return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
	}


	public function getPrevtimeTextAttr($value, $data)
	{
		$value = $value ? $value : ($data['prevtime'] ?? "");
		return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}

	public function getLogintimeTextAttr($value, $data)
	{
		$value = $value ? $value : ($data['logintime'] ?? "");
		return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}

	public function getJointimeTextAttr($value, $data)
	{
		$value = $value ? $value : ($data['jointime'] ?? "");
		return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}

	protected function setPrevtimeAttr($value)
	{
		return $value && !is_numeric($value) ? strtotime($value) : $value;
	}

	protected function setLogintimeAttr($value)
	{
		return $value && !is_numeric($value) ? strtotime($value) : $value;
	}

	protected function setJointimeAttr($value)
	{
		return $value && !is_numeric($value) ? strtotime($value) : $value;
	}

	protected function setBirthdayAttr($value)
	{
		return $value ? $value : NULL;
	}

	public static function syncData($output = NULL)
	{
		$departments = UserDepartment::where(['status' => 'normal'])->select();
		if ($departments) {
            User::update(['status' => 'hidden'], ['status' => 'normal']);
			$config = get_addon_config('thirdwork');
			$app    = new Application($config);
			foreach ($departments as $department) {
				$list = $app->wechatwork->getDepartmentUserList($department['id']);
				if ($list['code'] == 1 && $list['data']) {
					foreach ($list['data'] as $item) {
						$data  = [
							'username'      => $item['userid'],
							'nickname'      => $item['name'],
							'weigh'         => $item['order'],
							'position'      => $item['position'],
							'status'        => $item['active'] ? 'normal' : 'hidden',
							'department_id' => $department['id']
						];
						$check = User::get(['username' => $item['userid']]);
						if ($check) {
							if ($output) {
								$output->info('[' . date('Y-m-d H:i:s') . '] 更新员工：' . $item['name']);
							}
							User::update($data, ['username' => $item['userid']]);
						} else {
							$salt = Random::alnum();
							$ip   = request()->ip();
							$time = time();
							$data = array_merge($data, [
								'email'    => '',
								'mobile'   => '',
								'avatar'   => '/assets/img/avatar.png',
								'password' => md5(md5('123456') . $salt),
								'salt'     => $salt,
								'jointime' => $time,
								'joinip'   => $ip,
								'group_id' => 1
							]);
							if ($output) {
								$output->info('[' . date('Y-m-d H:i:s') . '] 创建员工：' . $item['name']);
							}
							User::create($data);
						}
					}
				}
			}
		}
	}

	public function group()
	{
		return $this->belongsTo('UserGroup', 'group_id', 'id', [], 'LEFT')->setEagerlyType(0);
	}

}
